//Copyright (C) 2008 QMTech (http://www.qmtech.net)

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Collections.Generic;

using MonoDevelop.Projects.Dom;
using MonoDevelop.Xml.StateEngine;
using MonoDevelop.Ide.Gui.Components;
using MonoDevelop.AspNet.Gui;

namespace MonoDevelop.Castle.Monorail
{
	
	sealed class HtmlEditorExtension : BaseHtmlEditorExtension
	{
		protected override IEnumerable<string> SupportedExtensions {
			get {
        		yield return ".vm";
				yield return ".htm";
			}
		}
		
		protected override void RefillOutlineStore (ParsedDocument doc, Gtk.TreeStore store)
		{
			XDocument xdoc = ((XmlParsedDocument)doc).XDocument;
			if (xdoc == null)
				return;
			BuildTreeChildren (store, Gtk.TreeIter.Zero, xdoc);
		}
		
		protected override void InitializeOutlineColumns (PadTreeView outlineTree)
		{
      		Gtk.CellRendererText crt = new Gtk.CellRendererText ();
			crt.Xpad = 0;
			crt.Ypad = 0;
			outlineTree.AppendColumn ("Node", crt, new Gtk.TreeCellDataFunc (outlineTreeDataFunc));
		}
		
		protected override void OutlineSelectionChanged (object selection)
		{
			SelectNode ((XNode)selection);
		}
		
		static void BuildTreeChildren (Gtk.TreeStore store, Gtk.TreeIter parent, XContainer p)
		{
			foreach (XNode n in p.Nodes) {
				Gtk.TreeIter childIter;
				if (!parent.Equals (Gtk.TreeIter.Zero))
					childIter = store.AppendValues (parent, n);
				else
					childIter = store.AppendValues (n);
				
				XContainer c = n as XContainer;
				if (c != null && c.FirstChild != null)
					BuildTreeChildren (store, childIter, c);
			}
		}
		
		void outlineTreeDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			Gtk.CellRendererText txtRenderer = (Gtk.CellRendererText) cell;
			XNode n = (XNode) model.GetValue (iter, 0);
			txtRenderer.Text = n.FriendlyPathRepresentation;
		}
		
		void SelectNode (XNode n)
		{
			MonoDevelop.Projects.Dom.DomRegion region = n.Region;
			
			XElement el = n as XElement;
			if (el != null && el.IsClosed && el.ClosingTag.Region.End > region.End) {
				region.End = el.ClosingTag.Region.End;
			}
			
			int s = Editor.GetPositionFromLineColumn (region.Start.Line, region.Start.Column);
			int e = Editor.GetPositionFromLineColumn (region.End.Line, region.End.Column);
			if (e > s && s > -1)
				Editor.Select (s, e);
		}
	}
}
